package com.tanker.util.httpUtil;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 闪银接口工具类
 * Created by renbin.fang on 2015/9/17.
 */
public class WeCashUtils {
    /**
     * wecash接口调用方法
     * @param uri 访问路径
     * @param jsonData 实际参数
     * @param userName 授权用户名
     * @param password  授权密码
     * @return
     * @throws IOException
     */
    public static String postJson(String uri, String jsonData, String userName,
                             String password) throws  IOException {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));

        CloseableHttpClient client = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credentialsProvider).build();
        HttpPost post = new HttpPost(uri);

        StringEntity par = new StringEntity(jsonData,
                HTTP.PLAIN_TEXT_TYPE, "UTF-8");
        post.setEntity(par);

        HttpResponse response = client.execute(post);
        int httpCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();


        return EntityUtils.toString(entity);
    }
}
